package com.koron.common.core.business.system.tree;

import org.apache.commons.codec.binary.StringUtils;
import org.apache.commons.collections4.CollectionUtils;

import java.util.*;

/**
 * @ClassName TreeUtil
 * @description
 * @Author zhouj
 * @Date 2021/6/3 15:58
 */
public class TreeUtil {

    //默认正序
    public static <V extends SuperTree> List<V> getTree(List<V> vlist) {

        return getTree(vlist, 1);

    }

    //默认正序
    public static <V extends SuperTree> List<V> getTreeNoOrder(List<V> vlist) {

        return getTree(vlist, null);

    }

    //传入list，返回树
    //order 自定义排序
    public static <V extends SuperTree> List<V> getTree(List<V> vlist, Integer order) {

        List<V> list = vlist;
        if (order != null) {
            list = order(vlist, order);
        }

        //返回的树
        List<V> roots = new ArrayList<>();
        //将数据添加到map
        Map<String, V> map = new HashMap<>();

        list.stream().forEach(tree -> map.put(tree.getId(), tree));

        list.forEach(p -> {
            //1.判断是否存在父节点

            V v = map.get(p.getParentid());

            if (null == v) {    //说明是顶级节点
                roots.add(map.get(p.getId()));
            } else {        //找到父节点添加，添加到父节点的children字段
                //1.获取到父对象
                V child = map.get(p.getParentid());

                //2.将对象添加到父对象的children
                child.getChildren().add(p);
            }
        });
        return roots;
    }

    //排序
    public static <V extends SuperTree> List<V> order(List<V> list, Integer order) {

        if (order != null && order == -1) {
            list.sort(Comparator.comparing(V::getOrder).reversed());
        } else {
            list.sort(Comparator.comparing(V::getOrder));
        }

        return list;
    }

    //获取父节点及以下节点
    public static <V extends SuperTree> List<V> search(List<V> list, List<V> arrayList, String parentid) {

        for (V v : list) {
            //1.判断是否存在父节点
            if (StringUtils.equals(v.getId(), parentid)) {
                arrayList.add(v);
            } else {
                if (arrayList.size() > 0) {
                    break;
                }
                List children = v.getChildren();
                if (children.size() > 0) {
                    search(children, arrayList, parentid);
                }
            }
            if (arrayList.size() > 0) {
                break;
            }
        }

        return arrayList;
    }

    //tree--list
    public static <V extends SuperTree> List<V> getList(List<V> list, List<V> arrayList) {

        list.forEach(p -> {
            //1.判断是否存在父节点
            arrayList.add(p);
            List<V> children = p.getChildren();
            if (!CollectionUtils.isEmpty(children)) {
                getList(children, arrayList);
            }
        });

        return arrayList;
    }

}